#include <WiFi.h>
#include <PubSubClient.h>
#include <WiFiUdp.h>

const char* ssid = "xxxxx";
const char* password = "xxxxx";
const char* mqtt_server = "xx.xx.xx.xx";
const int mqtt_port = 1883;

WiFiClient espClient;
PubSubClient client(espClient);

byte packet[102];
byte mac[6] = {0xFC, 0x34, 0x97, 0xB9, 0xF7, 0xA6};

void setup_wifi() {
  delay(10);
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();
  String isopen = "";
  for(int i=0;i<4;i++){
    isopen+=(char)payload[i];
  }
  if(isopen == "open"){
    WiFiUDP udp;
    memset(packet, 0xff, 6);
    for (int i = 0; i < 16; i++)
    {
        memcpy(packet + 6 + i * 6, mac, 6);
    }
    udp.beginPacket(IPAddress(192,168,52,255), 9);
    udp.write(packet, sizeof(packet));
    udp.endPacket();
    Serial.println("Magic packet sent");
  }
}

void setup_mqtt() {
  client.setServer(mqtt_server, mqtt_port);
  client.setCallback(callback);

  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    if (client.connect("ESP32Client")) {
      Serial.println("connected");
      client.subscribe("wol");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      delay(5000);
    }
  }
}

void setup() {
  Serial.begin(115200);
  setup_wifi();
  setup_mqtt();
}

void loop() {
  if (!client.connected()) {
    setup_mqtt();
  }
  client.loop();
}
